
/**
 * @version $Id$
 * @author xjiujiu <xjiujiu@foxmail.com>
 * @description HongJuZi Framework
 * @copyright Copyright (c) 2011-2012 http://www.xjiujiu.com.All right reserved
 */

HHJsLib.register({
    init: function() {
        this.bindBtnFinish();
        this.bindBtnTui();
        this.bindBtnPlus();
        this.bindTimer();
        this.bindBtnCancel();
        this.bindBtnFacePay();
        this.bindBtnCaiStart();
        this.bindBtnCaiDone();
        this.bindModalHide();
        this.bindBtnStuffOrder();
        this.bindBtnVipOrder();
        this.bindBtnGaiJia();
        this.bindBtnGuaDan();
        this.bindZaiDianPrinterTypeChange();
        this.bindBtnPrintInChuFang();
        this.bindBtnPrintCai('a.btn-print-cai');
        this.bindBtnPrintAllToChuFang();
        this.bindBtnPrintToGuest();
        this.bindBtnHuanHao();
        this.bindBtnGuestPayByQr();
        this.bindBtnCancelVip();
        this.bindBtnCancelGaiJia();
        this.bindBtnTuiAll();
        this.bindBtnAddCaiQuick();
        this.bindResetPrint('a.btn-reset-print');
        this.bindBtnFaPiao();
        this.bindBtnPrintToJieZhang();
        this.bindBtnPrintToDuiZhang();
        this.bindBtnZhuoHaoShow();
        this.bintBtnZhuoHaoClick('#zhuohao-list-box a.active');
        this.bindBtnCaiQuery();
        this.bindSearchZhuoHaoChange();
        this.bindBtnZhuoHaoKaiTai();
        this.initCurZhuoHaoShow();
        this.bindBtnUserWait();
    },
    bindBtnUserWait: function() {
        $('a.btn-waiting').click(function() {
            var id      = $(this).attr('data-id');
            var $this   = $(this);
            $.getJSON(
                queryUrl + 'admin/order/auserwait',
                {id: id},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    if(1 == response.data.status) {
                        $('#label-waiting-' + id).hide();
                        $this.html('<i class="ali-iconfont icon-time"></i> 客人等叫');
                    } else {
                        $('#label-waiting-' + id).show();
                        $this.html('<i class="ali-iconfont icon-time"></i> 取消等叫');
                    }
                    HHJsLib.succeed('操作成功！');
                }
            );
        });
    },
    bindSearchZhuoHaoChange: function() {
        $('#search-zhuohao').bind('keyup', function() {
            var val = $(this).val();
            var ids = [];
            if(!val) {
                $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').show();
                return;
            }
            val     = val.toUpperCase();
            $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').hide();
            for(var ele in orderMap) {
                if(0 > orderMap[ele].id.toString().indexOf(val)) {
                    continue;
                }
                $('#zhuohao-list-box div.zhuohao-item-box-' + orderMap[ele].id)
                .addClass('search-item').show();
            }
        }).bind('keydown', function(e) {
            if (e.keyCode != 13) {
                return;
            }
            $('#zhuohao-list-box div.zhuohao-item-box.search-item > a').first().click();
        }).bind('blur', function() {
            $(this).val('');
            $('#zhuohao-list-box div.zhuohao-item-box').removeClass('search-item').show();
        });
    },
    bindBtnZhuoHaoKaiTai: function() {
        var self    = this;
        $('#btn-new-order').click(function() {
            $('#modal-title').html('新外送订单');
            $('#modal-body').html($('#waisong-kaitai-list-tpl').html());
            $('#modal-footer').html($('#kaitai-footer-tpl').html());
            $('#myModal').modal('show');
            self.bindBtnKaiTaiConfirm();
        });
    },
    bindBtnKaiTaiConfirm: function() {
        var self    = this;
        $('#btn-tui-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#ws-name', '联系人姓名');
                HHJsLib.isPhoneByDom('#ws-phone', '联系人电话');
                HHJsLib.isEmptyByDom('#ws-address', '联系人地址');
                HHJsLib.info('正在努力操作中，请稍等...');
                HJZCommon.isLoading = true;
                $.getJSON(
                    queryUrl + 'admin/order/anewwaisong',
                    {
                        people: $('#kt-total-people').val(), 
                        name: $('#ws-name').val(), 
                        phone: $('#ws-phone').val(), 
                        address: $('#ws-address').val()
                    },
                    function(response) {
                        HJZCommon.isLoading = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('开台成功，正在加载中...');
                        window.location.href    = queryUrl + "admin/waisong?add=1&id=" + response.id;
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bintBtnZhuoHaoClick: function(dom) {
        var title           = $('title').text();
        $(dom).click(function() {
            var $this       = $(this);
            var id          = $this.attr('data-id');
            $('#zhuohao-list-box a.current').removeClass('current');
            $this.addClass('current');
            history.pushState({page: 1}, title, queryUrl + 'admin/waisong?id=' + id);
            if(0 == id) {
                return;
            }
            $('#order-list-box div.show').hide().removeClass('show');
            $('#zhuo-hao-order-box-' + id).addClass('show').show();
        });
    },
    initCurZhuoHaoShow: function() {
        if(curOrderId) {
            $('#zhuo-hao-item-' + curOrderId).click();
            if(add) {
                $('#btn-add-cai-' + curOrderId).click();
            }
        } else {
            this.setFirstActiveZhuoHao();
        }
    },
    bindBtnZhuoHaoShow: function() {
        $('#filter-search-box a.btn-area-show').click(function() {
            var id  = $(this).attr('data-id');
            $('#filter-search-box a.btn-area-show').removeClass('btn-primary');
            $(this).addClass('btn-primary');
            if(id <= 0) {
                $('#zhuohao-list-box div.zhuohao-item-box').show();
                return;
            }
            $('#zhuohao-list-box div.zhuohao-item-box').hide();
            $('#zhuohao-list-box div.area-' + id).show();
            return;
        });
    },
    bindBtnPrintToJieZhang: function() {
        $('a.btn-print-jie-zhang').click(function() {
            var id  = $(this).attr('data-id');
            $.getJSON(
                queryUrl + 'admin/printertask/aprintjiezhang',
                {id: id},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('发送打印结账单成功！');
                }
            );
        });
    },
    bindBtnPrintToDuiZhang: function() {
        $('a.btn-print-dui-zhang').click(function() {
            var id  = $(this).attr('data-id');
            $.getJSON(
                queryUrl + 'admin/printertask/aprintduizhang',
                {id: id},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('发送打印对账单成功！');
                }
            );
        });
    },
    bindBtnSetTotalPeople: function() {
        $('a.set-total-people').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('人数设置');
            $('#modal-body').html($('#total-people-body-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            $('#myModal').modal('show');
        });
    },
    bindBtnFaPiao: function() {
        var self    = this;
        $('a.btn-fapiao').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('发票设置');
            $('#modal-body').html($('#fapiao-body-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            $('#myModal').modal('show');
            $('#cur-order-id').val(id);
            self.bindBtnFapiaoSure();
        });
    },
    bindBtnFapiaoSure: function() {
        $('#btn-tui-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#cur-order-id', '订单编号');
                HHJsLib.isEmptyByDom('#fapiao-money', '发票金额');
                var id  = $('#cur-order-id').val();
                var money = $('#fapiao-money').val();
                $.getJSON(
                    queryUrl + 'admin/order/aeditfapiao',
                    {id: id, money: money},
                    function(response) {
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('设置成功！');
                        $('#fapiao-amount-' + id).html(money);
                        $('#myModal').modal('hide');
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindResetPrint: function(dom) {
        $(dom).click(function() {
            var id  = $(this).attr('data-goods-id');
            if(!confirm('确定要重打吗？')) {
                return;
            }
            $.getJSON(
                queryUrl + 'admin/ordergoods/asetprint',
                {id: id},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#zd-item-' + id + ' span.label-print').hide();
                    HHJsLib.succeed('清除成功！');
                }
            );
        });
    },
    bindBtnAddCaiQuick: function() {
        var self    = this;
        $('#btn-add-cai-quick').click(function() {
            $('#add-cai-modal').modal('hide');
            $.getJSON(
                queryUrl + 'admin/goodscategory/alist',
                {},
                function(response){
                    if(response.rs == false){
                        return HHJsLib.warn(response.message);
                    }
                    var html    = '<option value="">请选择</option>';
                    var content = html;
                    var cate    = response.data.category;
                    var list    = response.data.printer;
                    for(var i in list){
                        var item = list[i];
                        content    += '<option value="' + item.id + '">' + item.name + '</option>';
                    }
                    for(var i in cate){
                        var item = cate[i];
                        html    += '<option value="' + item.id + '">' + item.name + '</option>';
                    }
                    var tpl     = $('#add-cai-body-tpl').html();
                    tpl         = tpl.replace(/{category}/ig, html).replace(/{printer}/ig, content);
                    $('#modal-title').html('加自定义菜品');
                    $('#modal-body').html(tpl);
                    $('#modal-footer').html($('#tui-footer-tpl').html());
                    $('#myModal').modal('show');
                    self.bindBtnAddCaiQuickConfirm();
                }
            );
        });
    },
    bindBtnAddCaiQuickConfirm: function(){
      var self = this;
      $('#btn-tui-confrim').click(function(){
          try{
              HHJsLib.isEmptyByDom('#cai-name', '菜名');
              HHJsLib.isEmptyByDom('#cai-cat', '菜品分类');
              HHJsLib.isEmptyByDom('#cai-price', '价格');
              HHJsLib.isEmptyByDom('#cai-printer', '对应打印机');
              var orderId = $('#cur-order-id').val();
              HHJsLib.isEmpty(orderId, '餐桌号');
              var name  = $('#cai-name').val();
              var catId = $('#cai-cat').val();
              var price = $('#cai-price').val();
              var printer = $('#cai-printer').val();
              $.getJSON(
                  queryUrl + 'admin/diancan/addcaiquick',
                  {name: name, cat_id: catId, price: price, printer: printer, order_id: orderId},
                  function(response){
                      if(response.rs == false){
                          return HHJsLib.warn(response.message);
                      }
                      HHJsLib.succeed('加菜成功！');
                      var data    = response.data;
                      var tpl     = $('#plus-goods-item-tpl').html();
                      tpl         = tpl.replace(/{order_goods_id}/ig, data.goods_id)
                          .replace(/{id}/ig, orderId)
                          .replace(/{name}/ig, data.name)
                          .replace(/{group_name}/ig, data.group_name)
                          .replace(/{price}/ig, data.price)
                          .replace(/{vip_price}/ig, data.vip_price)
                          .replace(/{src_price}/ig, data.src_price)
                          .replace(/{number}/ig, data.number)
                          .replace(/{order_id}/ig, orderId)
                          .replace(/{order_goods_id}/ig, data.id)
                          .replace(/{printer_id}/ig, data.printer_id)
                          .replace(/{printer_name}/ig, data.printer_name)
                          .replace(/{number}/ig, data.number)
                          .replace(/{discount}/ig, data.discount)
                          .replace(/{total_price}/ig, data.total_price);
                      $('#data-grid-box-' + orderId).find('tbody').prepend(tpl);
                      $('#item-total-number-' + orderId).html(data.total_number);
                      $('#item-total-amount-' + orderId).html(data.amount);
                      $('strong.src-amount-' + orderId + " span.amount").html(data.src_amount);
                      $('#item-total-src-amount-' + orderId).html(data.src_amount);
                      $('#item-pay-money-' + orderId).html(data.pay_money);
                      if(parseFloat(data.youhui) > 0){
                          $('#use-youhui-' + orderId).html('优惠：' + response.data.youhui + ' 元 ').show();
                      }else{
                          $('#use-youhui-' + orderId).hide();
                      }
                      self.bindResetPrint('#zd-od-item-' + data.goods_id + ' a.btn-reset-print');
                      self.bindBtnPrintCai('#zd-od-item-' + data.goods_id + ' a.btn-print-cai');
                      self.bindBtnTui();
                      $('#myModal').modal('hide');
                  }
              );
          }catch(e){
              return HHJsLib.warn(e);
          }
      });
    },
    bindBtnTuiAll: function() {
        $('a.btn-tui-all').click(function() {
            if(!confirm('确认要整桌退吗？')) {
                return;
            }
            var id  = $(this).attr('data-id');
            HJZCommon.isLoading = true;
            $.getJSON(
                queryUrl + 'admin/order/atuiall',
                {id: id},
                function(response) {
                    HJZCommon.isLoading = true;
                    if(false == response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('整桌退菜打印成功！');
                }
            );
        });
    },
    bindBtnCancelGaiJia: function() {
        $('a.btn-cancel-gaijia').click(function() {
            var id  = $(this).attr('data-id');
            $.getJSON(
                queryUrl + 'admin/order/acancelgaijia',
                {id: id},
                function(response) {
                    if(false == response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('取消成功！');
                    $('#item-total-amount-' + id).html(response.data.amount);
                    $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                    $('#item-pay-money-' + id).html(response.data.pay_money);
                    $('#item-zhekou-' + id).html(response.data.zhekou);
                    $('#item-zhekou-amount-' + id).html(response.data.zhekou_amount);
                    $('#myModal').modal('hide');
                }
            );
        });
    },
    bindBtnCancelVip: function() {
        $('a.btn-cancel-vip').click(function() {
            var id  = $(this).attr('data-id');
            $.getJSON(
                queryUrl + 'admin/order/acancelvip',
                {id: id},
                function(response) {
                    if(false == response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('取消成功！');
                    $('#item-total-amount-' + id).html(response.data.amount);
                    $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                    $('#item-pay-money-' + id).html(response.data.pay_money);
                    $('#item-zhekou-' + id).html(response.data.zhekou);
                    $('#item-zhekou-amount-' + id).html(response.data.zhekou_amount);
                    $('#data-grid-box-' + id).children('tbody').children('tr').each(function(){
                        var $this = $(this);
                        var srcPrice    = parseFloat($this.children('td:eq(3)').text());
                        var vipPrice    = parseFloat($this.children('td:eq(2)').text());
                        var number      = parseFloat($this.children('td:eq(5)').text());
                        if(isNaN(vipPrice)){
                            return false;
                        }
                        var total       = srcPrice * number;
                        $this.children('td:eq(6)').text(total.toFixed(2));
                        $this.children('td:eq(1)').text(srcPrice);
                    });
                }
            );
        });
    },
    bindBtnVipOrder: function() {
        $('a.btn-vip-order').click(function() {
            var that    = $(this);
            var id      = $(this).attr('data-id');
            var load    = $(this).attr('data-load');
            if(load == 2){
                return false;
            }
            that.attr('data-load', 2);
            var data    = {
                uid: $(this).attr('data-uid'), 
                id: $(this).attr('data-id')
            };
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/order/avip',
                data,
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    that.attr('data-load', 1);
                    HHJsLib.succeed('设置成功');
                    $('#item-total-amount-' + id).html(response.data.amount);
                    $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                    $('#item-pay-money-' + id).html(response.data.pay_money);
                    $('#item-zhekou-amount-' + id).html(response.data.zhekou_amount);
                    $('#data-grid-box-' + id).children('tbody').children('tr').each(function(){
                        var $this = $(this);
                        var vipPrice    = parseFloat($this.children('td:eq(2)').text());
                        var number      = parseFloat($this.children('td:eq(5)').text());
                        if(isNaN(vipPrice)){
                            return false;
                        }
                        var total       = vipPrice * number;
                        $this.children('td:eq(6)').text(total.toFixed(2));
                        $this.children('td:eq(1)').text(vipPrice);
                    });
                }
            );
        });
    },
    bindBtnGuestPayByQr: function() {
        $('#btn-guest-pay-qr').click(function() {
            var src     = $(this).attr('data-qr');
            $('#qr-modal-body').html('<img src="' + src + '" width="300"/>');
            $('#qr-pay-modal-common').modal('show');
        });
    },
    bindBtnMergePay: function() {
        var self = this;
        $('#btn-merge-pay').click(function() {
            $('#modal-title').html('合并支付');
            $('#modal-body').html($('#merge-pay-list-tpl').html());
            $('#modal-footer').html($('#pay-cash-footer-tpl').html());
            $('#myModal').modal('show');
            self.bindBtnAddPayment();
            self.loadMergeOrderList();
            self.bindPayAmountChange('#user-payment-list-box input.payment-money');
            self.bindPostMergeOrderForm();
        });
    },
    bindPostMergeOrderForm: function() {
        var self    = this;
        $('#btn-sure-cash').click(function() {
            try {
                HHJsLib.isEmptyByDom('#need-pay-money', '应付金额');
                HHJsLib.isEmptyByDom('#money', '实付金额');
                HHJsLib.isEmptyByDom('#payment', '支付方式');
                self.postFacePay(
                    queryUrl + 'payment/payment/apaybycashmerge',
                    $('#form-pay-by-cash').serializeArray(),
                    '#myModal'
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    loadMergeOrderList: function() {
        var self    = this;
        HJZCommon.isLoading = true;
        $.getJSON(
            queryUrl + 'admin/diancan/amergelist',
            {},
            function(response) {
                HJZCommon.isLoading = false;
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                var html    = '';
                var tpl     = $('#merge-order-item-tpl').html();
                for(var ele in response.data) {
                    var item = response.data[ele];
                    html += tpl.replace(/{zhuohao_name}/ig, item.zhuohao_name)
                    .replace(/{amount}/ig, item.amount)
                    .replace(/{id}/ig, item.id);
                }
                $('#zhuohao-all-list-box').html(html);
                self.bindSelectMergeZhuoHaoClick();
            }
        );
    },
    bindSelectMergeZhuoHaoClick: function() {
        var self    = this;
        $('#zhuohao-all-list-box .item label input').click(function() {
            var id      = $(this).val();
            var amount  = parseFloat($(this).attr('data-amount'));
            var needPay = $('#need-pay-money').val();
            needPay     = !needPay ? 0 : parseFloat(needPay);
            if($(this).prop('checked')) {
                needPay += amount;
            } else {
                needPay -= amount;
            }
            $('#need-pay-money').val(needPay.toFixed(2));
            self.reCountUserPay();
        });
    },
    bindBtnHuanHao: function() {
        var self = this;
        $('a.btn-gaizhuohao').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('更换客人桌号');
            $('#modal-body').html($('#yd-zhuohao-list-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/zhuohao/auselist',
                {},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    if(1 > response.data.length) {
                        return HHJsLib.warn('桌位已满，请客人稍等一下！');
                    }
                    var opt     = '<option value="">请选择桌号</option>';
                    for(var ele in response.data) {
                        var item= response.data[ele];
                        opt     += '<option value="' + item.id + '">桌号：' + item.name + '</option>';
                    }
                    $('#yd-zhuohao-list').html(opt);
                    $('#myModal').modal('show');
                    self.bindBtnConfirmChangeZhuoHao(id);
                }
            );
        });
    },
    bindBtnConfirmChangeZhuoHao: function(id) {
        $('#btn-tui-confrim').click(function() {
            var zhuoHaoId   = $('#yd-zhuohao-list').val();
            $.getJSON(
                queryUrl + 'admin/order/achangezhuohao',
                {id: id, zhuohao: zhuoHaoId},
                function(response) {
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    $('#myModal').modal('hide');
                    HHJsLib.succeed('更换成功，即将刷新请稍等...');
                    setTimeout(function() {
                        window.location.href    = queryUrl + 'admin/diancan?code=' + zhuoHaoId;
                    }, 500);
                }
            );
        });
    },
    bindBtnPrintToGuest: function() {
        var self = this;
        $('a.btn-print-to-guest').click(function() {
            self.doPrintOrderToGuest($(this));
        });
    },
    doPrintOrderToGuest: function($this) {
        var id      = $this.attr('data-id');        
        var type    = $this.attr('data-type');
        var data    = {
            id: id,
            type: type
        };
        this.postPrinterTask(queryUrl + 'admin/printertask/apostforguest', data, null);
    },
    bindBtnPrintAllToChuFang: function() {
        var self    = this;
        $('a.btn-print-all-in-chufang, a.btn-print-all-cui-cai, a.btn-print-all-shang-cai').click(function() {
            if(!confirm("您确认要一键发送给厨房吗？")) {
                return false;
            }
            var id      = $(this).attr('data-id');
            var type    = $(this).attr('data-type');
            var data    = {
                id: id,
                type: type,
                'parent_id': []
            };
            $('#order-printer-list-' + id + ' a.btn-print-in-chufang').each(function() {
                data.parent_id.push($(this).attr('data-printer-id'));
            });
            self.postPrinterTask(queryUrl + 'admin/printertask/apostbyall', data);
        });
    },
    bindBtnPrintCai: function(dom) {
        var self    = this;
        $(dom).click(function() {
            if(!confirm("您确认要执行这个操作吗？")) {
                return false;
            }
            var id  = $(this).attr('data-id');
            var gId = $(this).attr('data-goods-id');
            var pId = $(this).attr('data-printer-id');
            var url = queryUrl + 'admin/diancan/printchufangcai?id=' + id + '&gId=' + gId;
            if(true == self.doPrinting(url, gId, id)) {
                return;
            }
            var type = $(this).attr('data-type');
            var data    = {
                'og_id': gId,
                'parent_id': pId,
                'id': id,
                'type': type
            };
            self.postPrinterTask(queryUrl + 'admin/printertask/apostbycai', data);
        });
    },
    doPrinting: function(url, ids, id) {
        return false;
        window.open(
            url,
            "_blank",
            "toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes"
        );
        this.bindBtnPrintSuccess(ids);

        return true;
    },
    postPrinterTask: function(url, data) {
        var self                = this;
        HJZCommon.isLoading     = true;
        $.post(
            url,
            data,
            function(response) {
                HJZCommon.isLoading     = false;
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                if(response.ids && 0 < response.ids.length) {
                    self.showZDItemPrint(response.ids);
                }
                HHJsLib.succeed('订单#' + response.ids + '打印任务发送成功！');
            },
            'json'
        );
    },
    showZDItemPrint: function(ids) {
        for(var ele in ids) {
            var id  = ids[ele];
            $('#zd-item-' + id + ' span.label-print').removeClass('hide').show();
        }
    },
    bindPayAmountChange: function(dom) {
        var self    = this;
        $(dom).bind('keyup change', function() {
            self.reCountUserPay();
        });
    },
    reCountUserPay: function() {
        var paymentAmount   = 0;
        var payMoney        = parseFloat($('#need-pay-money').val());
        $('input.payment-money').each(function() {
            var val     = $(this).val();
            val         = !val ? 0 : parseFloat(val);
            paymentAmount += val;
        });
        var zhaoLing    = (paymentAmount - payMoney).toFixed(2);
        $('#payment-amount').html('￥' + paymentAmount);
        $('#zhaoling-money').text('￥' + zhaoLing);
        $('#zhaoling-value').val(zhaoLing);
    },
    bindBtnAddPayment: function() {
        var t           = (new Date()).getTime();
        var self        = this;
        $('#btn-add-payment').click(function() {
            var tpl     = $('#payment-item-tpl').html();
            $('#append-payment-list-box').append(tpl.replace(/{t}/g, t));
            self.bindBtnSubPayment(t);
            self.bindPayAmountChange('#user-payment-list-box div.payment-' + t + ' input.payment-money');
            self.bindPaymentTypeChange();
            t ++;
        });
    },
    bindBtnSubPayment: function(t) {
        $('#btn-sub-payment-' + t).click(function() {
            var id  = $(this).attr('data-id');
            $('div.payment-' + id).remove();
        });
    },
    bindZaiDianPrinterTypeChange: function() {
        $('select.chufang-printer-type').bind('change', function() {
            var type  = $(this).val();
            var id  = $(this).attr('data-id');
            $('div#zaidian-printer-box-' + id + ' a.btn, #list-form-' + id + 'a.btn-print-cai').attr('data-type', type);
        });
    },
    bindBtnPrintInChuFang: function() {
        var self    = this;
        $('a.btn-print-in-chufang').click(function() {
            if(!confirm("您确认要执行这个操作吗？")) {
                return false;
            }
            var href    = $(this).attr('data-href');
            var type    = $(this).attr('data-type');
            var ids     = $(this).attr('data-ids');
            var id      = $(this).attr('data-id');
            if(true == self.doPrinting(href + '&type=' + type, ids, id)) {
                return;
            }
            var pId     = $(this).attr('data-printer-id');
            var data    = {
                'type': type,
                'id': id,
                'parent_id': pId
            };
            self.postPrinterTask(queryUrl + 'admin/printertask/apostbyprinter', data);
        });
    },
    bindBtnPrintSuccess: function(ids) {
        $('#modal-title').html('打印确认');
        $('#modal-body').html('<h3 class="text-center"><i class="icon icon-print fs-30"></i><br/>是否打印成功？</h3>');
        $('#modal-footer').html($('#yesno-footer-tpl').html());
        $('#myModal').modal('show');
        var self    = this;
        HJZCommon.isLoading     = true;
        $('#btn-tui-confrim').click(function() {
            $.getJSON(
                queryUrl + 'admin/ordergoods/aprint',
                {ids: ids},
                function(response) {
                    HJZCommon.isLoading     = false;
                    $('#myModal').modal('hide');
                    if(false === response.rs) {
                        return alert(response.message);
                    }
                    self.showZDItemPrint(ids);
                }
            );
        });
    },
    bindBtnGuaDan: function() {
        var self    = this;
        $('a.btn-guadan').click(function() {
            var id  = $(this).attr('data-id');
            $('#modal-title').html('设置对应的挂单客户');
            $('#modal-body').html($('#guadan-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            $('#myModal').modal('show');
            self.initSelectEffect('#myModal select');
            self.bindGuaDanBtnConfirm(id);
        });
    },
    initSelectEffect: function(dom) {
        HHJsLib.importCss([cdnUrl + "/jquery/plugins/chosen/chosen.css"]);
        HHJsLib.importJs([cdnUrl + "/jquery/plugins/chosen/chosen.jquery.js"], function() {
            $(dom).chosen({no_results_text: "没有找对应内容!"}); 
        });
    },
    bindGuaDanBtnConfirm: function(id) {
        $('#btn-tui-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#guadan-user-id', '挂单客户');
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/order/aguadan',
                    {
                        id: id, 
                        user_id: $('#guadan-user-id').val(), 
                        comment: $('#comment').val(),
                        type: $('#guadan-type').val()
                    },
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('挂单设置成功！');
                        $('#myModal').modal('hide');
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnGaiJia: function() {
        var self    = this;
        $('a.btn-gaijia').click(function() {
            var id  = $(this).attr('data-id');
            var items       = $("#item-total-number-" + id).text();
            $('#modal-title').html('订单菜品改价（共' + items + '件）');
            $('#modal-body').html($('#gaijia-tpl').html());
            $('#modal-footer').html($('#tui-footer-tpl').html());
            $('#myModal').modal('show');
            $('#discount').attr('data-id', id);
            $('#pay-money-price').html($('#item-pay-money-' + id).html());
            $('#src-price').html($('#item-total-amount-' + id).html());
            $('#src-amount-price').html($('#item-total-src-amount-' + id).html());
            self.bindGaiJiaBtnConfirm(id);
        });
    },
    bindGaiJiaBtnConfirm: function(id) {
        $('#btn-tui-confrim').click(function() {
            try {
                var discount    = $('#modal-discount').val();
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/order/agaijia',
                    {id: id, discount: discount, price: $('#modal-price').val()},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('改价成功');
                        $('#item-total-amount-' + id).html(response.data.amount);
                        $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                        $('#item-pay-money-' + id).html(response.data.pay_money);
                        $('#item-zhekou-' + id).html(response.data.zhekou);
                        $('#item-zhekou-amount-' + id).html(response.data.zhekou_amount);
                        $('#myModal').modal('hide');
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnStuffOrder: function() {
        var self    = this;
        $('a.btn-stuff-order').click(function() {
            var id  = $(this).attr('data-id');
            var uid = $(this).attr('data-uid');
            var amount      = $(this).attr('data-amount');
            var sum         = $(this).attr('data-sum');
            var stuffTpl    = $('#stuff-order-tpl').html();
            stuffTpl        = stuffTpl.replace(/{uid}/g, uid)
            .replace(/{amount}/g, amount)
            .replace(/{sum}/g, sum);
            $('#modal-title').html('员工代点订单切换<small>（VIP会员自动使用VIP价计算）</small>');
            $('#modal-body').html(stuffTpl);
            $('#modal-footer').html($('#user-pay-footer-tpl').html());
            $('#myModal').modal('show');
            self.bindBtnSearchUser(id);
            self.bindUseLingQianYouHuiJuanChange();
            self.bindBtnSureAndUserPay(id);
        });
    },
    bindBtnSureAndUserPay: function(id) {
        var self    = this;
        $('#btn-userpay-confrim').click(function() {
            try {
                HHJsLib.isEmptyByDom('#query', '搜索会员手机');
                HHJsLib.isEmptyByDom('#from-uid', '当前订单会员编号');
                HHJsLib.isEmptyByDom('#to-user-id', '支付会员编号');
                var useLingQian     = $('#user-lingqian-money').text();
                var useChongZhi     = $('#user-chongzhi-money').text();
                var data    = {
                    fid: $('#from-uid').val(), 
                    tid: $('#to-user-id').val(), 
                    yhid: $('#yd-zhuohao-list').val(), 
                    id: id, 
                    lingqian: useLingQian, 
                    chongzhi: useChongZhi
                };
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/order/aswitch',
                    data,
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('更新成功，可以继续下一步操作了哦～');
                        setTimeout(function() {
                            window.location.href    = queryUrl + 'admin/diancan?type=1&id=' + id;
                        }, 500);
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    postFacePay: function(url, data, dialogDom) {
        HHJsLib.info('正在努力操作中，请稍等...');
        var self                = this;
        HJZCommon.isLoading     = true;
        $.getJSON(
            url,
            data,
            function(response) {
                HJZCommon.isLoading  = false;
                if(false === response.rs) {
                    return HHJsLib.warn(response.message);
                }
                HHJsLib.succeed('付款操作成功！');
                $(dialogDom).modal('hide');
                $('#notice-myModal').modal('show');
                var loc     = 0;
                //开始发送打印内容
                var sendPrintTimer   = setInterval(function() {
                    if(false == HJZCommon.isLoading) {
                        var id = response.data[loc];
                        self.doPrintOrderToGuest($('#zhuo-hao-order-box-' + id + ' a.btn-print-to-guest'));
                        self.removeOrderItemBox(id);
                        $('#zhuo-hao-order-box-' + id).fadeOut('fast', function() {
                            $(this).remove();
                        });
                        self.setFirstActiveZhuoHao();
                        loc ++;
                        if(loc >= response.data.length) {
                            $('#notice-myModal').modal('hide');
                            clearInterval(sendPrintTimer);
                        }
                    }
                }, 1000);
            }
        );
    },
    //员工代点餐时的订单改价功能
    bindUseLingQianYouHuiJuanChange: function() {
        var self        = this;
        $('#btn-user-chongzhi').click(function() {
            var amount  = parseFloat($('#amount').text());
            var money   = parseFloat($(this).attr('data-money'));
            var sum     = parseFloat($('#order-sum').val());
            var sub     = money > sum ? money - sum : 0;
            sub         = sub.toFixed(2);
            if(amount <= 0 && $('#user-chongzhi').is(':checked')) {
                return false;
            }
            if($('#user-chongzhi').is(':checked')) {
                $('#user-chongzhi-money').text((money - sub).toFixed(2));
                $('#user-chongzhi-txt').text(sub);
            } else {
                $('#user-chongzhi-money').text('0');
                $('#user-chongzhi-txt').text(money);
            }
            self.reCountAmount();
        });
        $('#btn-user-lingqian').click(function() {
            var amount  = parseFloat($('#amount').text());
            var money   = parseFloat($(this).attr('data-money'));
            var sum     = parseFloat($('#order-sum').val());
            var sub     = money > sum ? money - sum : 0;
            sub         = sub.toFixed(2);
            if(amount <= 0 && $('#user-lingqian').is(':checked')) {
                return false;
            }
            if($('#user-lingqian').is(':checked')) {
                $('#user-lingqian-money').text(money - sub);
                $('#user-lingqian-txt').text(sub);
            } else {
                $('#user-lingqian-money').text('0');
                $('#user-lingqian-txt').text(money);
            }
            self.reCountAmount();
        });
    },
    reCountAmount: function() {
        var sum     = parseFloat($('#order-sum').val());
        var lingQian= parseFloat($('#user-lingqian-money').text());
        var chongZhi= parseFloat($('#user-chongzhi-money').text());
        var youHuiJuan  = parseFloat($('#user-youhuijuan-money').text());
        var amount      = sum - lingQian - chongZhi - youHuiJuan;
        amount          = 0 >= amount ? 0.00 : amount;
        $('#amount').text(amount.toFixed(2));
    },
    bindBtnSearchUser: function(id) {
        var self    = this;
        $('#btn-search-user').click(function() {
            try { 
                HHJsLib.isEmptyByDom('#query', '搜索关键字');
                HHJsLib.isEmptyByDom('#s-type', '搜索类别');
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/user/asearchforpay', 
                    {query: $('#query').val(), id: id, type: $('#s-type').val()},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(false === response.rs) {
                            return HHJsLib.warn(response.message);
                        }
                        self.setUserYouHuiJuanList(response.data.youhuijuan);
                        var avatar = '<img width="64" height="64" style="border-radius: 50%;" src="' 
                        + response.data.userInfo.avatar + '" /><br/>' + response.data.userInfo.name
                        + '（真实姓名：' + response.data.userInfo.true_name + '）';
                        $('#user-info-box').html(avatar);
                        $('#to-user-id').val(response.data.userInfo.id);
                        $('#user-lingqian-txt').html(response.data.userInfo.lingqian);
                        $('#user-chongzhi-txt').html(response.data.userInfo.chongzhi);
                        $('#btn-user-lingqian').attr('data-money', response.data.userInfo.lingqian);
                        $('#btn-user-chongzhi').attr('data-money', response.data.userInfo.chongzhi);
                        self.bindYHJChange();
                    }
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindYHJChange: function() {
        var self        = this;
        $('#yd-zhuohao-list').bind('change blur', function() {
            var id      = $('#yd-zhuohao-list').val();
            var money   = $('#yd-zhuohao-list').find("option:selected").attr('data-sub-money');
            $('#user-youhuijuan-money').text(money);
            self.reCountAmount();
        });
    },
    setUserYouHuiJuanList: function(list) {
        var opt     = '<option value="">请选择</option>';
        if(!list || 1 > list.length) {
            $('#yd-zhuohao-list').html(opt);
            return;
        }
        for(var ele in list) {
            opt     += '<option value="' + list[ele].id + '"'
            + 'data-sub-money="' + list[ele].sub_money + '"'
            + ' data-min-money="'+ list[ele].min_money + '">减'
            + list[ele].sub_money + '元，满' + list[ele].min_money +  '元</option>';
        }
        $('#yd-zhuohao-list').html(opt);
    },
    bindModalHide: function() {
        $('#myModal').on('hidden', function () {
            $('#modal-title').html('');
            $('#modal-body').html('');
            $('#modal-footer').html('');
        });
    },
    bindBtnCaiStart: function() {
        $('a.btn-cai-start').click(function() {
            var $this   = $(this);
            var $parent = $this.parent();
            var id      = $this.attr('data-id');
            var uid     = $this.attr('data-uid');
            if(!confirm('确认要执行此操作，此桌开始上菜了吗？')) {
                return;
            }
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/diancan/acaistart',
                {id: id, uid: uid},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('确认开始上菜成功！');
                    $this.fadeOut('fast', function() {
                        $this.remove();
                        $parent.find('a.btn-cai-done').show();
                    });
                }
            );
        });
    },
    bindBtnCaiDone: function() {
        $('a.btn-cai-done').click(function() {
            var $this   = $(this);
            var id      = $this.attr('data-id');
            var uid     = $this.attr('data-uid');
            if(!confirm('确认要执行此操作，此桌上菜完成了吗？')) {
                return;
            }
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/diancan/acaidone',
                {id: id, uid: uid},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    HHJsLib.succeed('确认完成上菜成功！');
                    $this.fadeOut('fast', function() {
                        $this.remove();
                    });
                }
            );
        });
    },  
    bindBtnSureCash: function() {
        var self    = this;
        $('#btn-sure-cash').click(function() {
            try {
                HHJsLib.isEmptyByDom('#need-pay-money', '应付金额');
                HHJsLib.isEmptyByDom('#money', '实付金额');
                HHJsLib.isEmptyByDom('#payment', '支付方式');
                var id  = $(this).attr('data-id');
                self.postFacePay(
                    queryUrl + 'payment/payment/apaybycash?id=' + id,
                    $('#form-pay-by-cash').serializeArray(),
                    '#myModal'
                );
            } catch(e) {
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnFacePay: function() {
        var self    = this;
        $('a.btn-facepay').click(function() {
            var id  = $(this).attr('data-id');
            $.getJSON(
                queryUrl + 'admin/diancan/isprint',
                {id: id},
                function(response){
                    if(false == response.rs){
                        return HHJsLib.warn(response.message);
                    }
                    $('#modal-title').html('输入面对面付款金额');
                    $('#modal-body').html($('#pay-cash-body-tpl').html());
                    $('#modal-footer').html($('#pay-cash-footer-tpl').html());
                    $('#myModal').modal('show');
                    $('#append-payment-list-box').html('');
                    $('#btn-sure-cash').attr('data-id', id);
                    var amount  = $.trim($('#item-total-amount-' + id).text());
                    $('#money').val(amount);
                    $('#need-pay-money').val(amount);
                    var discount    = Cookies.get('discount');
                    if(discount) {
                        $('#modal-discount').val(discount);
                    }
                    self.bindBtnSureCash();
                    self.bindBtnAddPayment();
                    self.bindPayAmountChange('#user-payment-list-box input.payment-money');
                    self.bindPaymentTypeChange();
                }
            );
        });
    },
    bindPaymentTypeChange: function(){
      var self = this;
        $('.payment').unbind().bind('change', function(){
            var t       = (new Date()).getTime();
            var that    = $(this);
            var type    = that.val();
            var tpl     = $('#guadan-tpl').html();
            var html    = tpl.replace(/{id}/ig, t);
            if(type == 6){
                that.parents('.control-group').after(html);
            }else{
                that.parents('.control-group').siblings('.qiandan-item-box').remove();
            }
        });
    },
    bindBtnCancel: function() {
        var self    = this;
        $('a.btn-cancel').click(function() {
            var id          = $(this).attr('data-id');
            if(!confirm('您真的要取消当前订单吗？注意：取消后不可恢复哦！')) {
                return;
            }
            HHJsLib.info('正在取消订单，请稍等...');
            HJZCommon.isLoading     = true;
            $.getJSON(
                queryUrl + 'admin/order/atrash',
                {id: id},
                function(response) {
                    HJZCommon.isLoading     = false;
                    if(false === response.rs) {
                        return HHJsLib.warn(response.message);
                    }
                    //还原到空闲状态.
                    self.removeOrderItemBox(id);
                    $('#zhuo-hao-order-box-' + id).fadeOut('fast', function() {
                        $(this).remove();
                    });
                    HHJsLib.succeed('取消成功！');
                    self.setFirstActiveZhuoHao();
                }
            );
        });
    },
    setFirstActiveZhuoHao: function() {
        var $curZhuoHao = $('#zhuohao-list-box a.active').first();
        if(1 > $curZhuoHao.length) {
            return;
        }
        var title   = $('title').text();
        $curZhuoHao.click();
        history.pushState({page: 1}, title, queryUrl + 'admin/waisong?id=' + $curZhuoHao.attr('data-id'));
    },
    removeOrderItemBox: function(id) {
        $('#zhuohao-item-box-' + id).fadeOut('fast', function() {
            $(this).remove();
        });
    },
    bindTimer: function(dom) {
        dom     = typeof(dom) == 'undefined' ? 'strong.time-box' : dom;
        var $dom        = $(dom);
        var time        = Math.floor((new Date()).getTime() / 1000);
        var timer       = setInterval(function() {
            $dom.each(function() {
                var $that       = $(this);
                var startTime   = $that.attr('data-time');
                var lastTime    = time - startTime;
                var min         = Math.floor(lastTime / 60);
                var sec         = lastTime - min * 60;
                var minStr      = min >= 10 ? min : (min <= 0 ? '00' : '0' + min);
                var secStr      = sec >= 10 ? sec : (sec <= 0 ? '00' : '0' + sec);
                $that.html(minStr + ':' + secStr);
                if(min > 45) {
                    $that.removeClass('label-info').addClass('label-danger');
                } else if(min > 25) {
                    $that.removeClass('label-info').addClass('label-warning');
                }
            });
            time ++;
        }, 1000);
    },
    bindBtnFinish: function(){
        var self = this;
        $('a.btn-finish').click(function(){
            var that        = $(this);
            var id          = that.attr('data-id');
            HHJsLib.confirm('确定客户已付款了', function(e){
                HJZCommon.isLoading     = true;
                $.getJSON(
                    queryUrl + 'admin/diancan/afinish',
                    {id: id},
                    function(response){
                        HJZCommon.isLoading     = false;
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                        self.removeOrderItemBox(id);
                        $('#zhuo-hao-order-box-' + id).fadeOut('fast', function() {
                            $(this).remove();
                        });
                        self.setFirstActiveZhuoHao();
                        HHJsLib.succeed('确认付款成功！');
                    }
                );
            });
        });
    },
    bindBtnTui: function(){
        var self    = this;
        $('a.btn-tui').click(function(){
            var that    = $(this);
            var id      = that.attr('data-id');
            var goodsId = that.attr('data-goods-id');
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(goodsId, '编号');
                $('#modal-title').html('退菜');
                var tpl     = $('#tui-content-tpl').html();
                var footer  = $('#tui-footer-tpl').html();
                var name    = that.parents('tr').children('td:eq(0)').children('strong.name').text();
                var price   = that.parents('tr').children('td:eq(1)').text();
                var number  = that.parents('tr').children('td:eq(5)').text();
                tpl         = tpl.replace(/{goods_name}/ig, name).replace(/{price}/ig, price)
                            .replace(/{number}/ig, number).replace(/{id}/ig, id).replace(/{order-goods-id}/ig, goodsId);
                $('#modal-body').html(tpl);
                $('.modal-footer').html(footer);
                $('#myModal').modal('show');
                self.bindBtnTuiConfirm();
            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnTuiConfirm: function(){
        $('#btn-tui-confrim').click(function(){
            var that    = $(this);
            var id      = $('#tui-goods').find('.order-id').val();
            var goodsId = $('#tui-goods').find('.order-goods-id').val();
            var oldNum  = parseInt($('#tui-goods').find('.number').val());
            var number  = parseInt($('#tui-goods').find('.goods-number').val());
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(goodsId, '编号');
                if(1 > number || number > oldNum){
                    return HHJsLib.warn('要退数量不正确');
                }                
                HJZCommon.isLoading     = true;
                HHJsLib.info('正在努力退菜中...');
                $.getJSON(
                    queryUrl + 'admin/diancan/atui',
                    {id: id, goods_id: goodsId, number: number},
                    function(response) {
                        HJZCommon.isLoading     = false;
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('退菜成功');
                        $('#myModal').modal('hide');
                        if(number < oldNum){
                            var price = (oldNum - number) * response.data.price;
                            $('#zd-od-item-' + goodsId).children('td:eq(4)').html(oldNum - number);
                            $('#zd-od-item-' + goodsId).children('td:eq(5)').html(price.toFixed(2));
                        }else{
                            $('#zd-od-item-' + goodsId).fadeOut('fast', function(){
                                $(this).remove();
                            });                                
                        }
                        $('#item-total-number-' + id).html(response.data.number);
                        $('#item-total-amount-' + id).html(response.data.amount);
                        $('strong.src-amount-' + id + " span.amount").html(response.data.src_amount);
                        $('#item-total-src-amount-' + id).html(response.data.src_amount);
                        $('#item-pay-money-' + id).html(response.data.pay_money);
                        if(parseFloat(response.data.youhui) > 0){
                            $('#use-youhui-' + id).html('优惠：' + response.data.youhui + ' 元 ').show();
                        }else{
                            $('#use-youhui-' + id).hide();
                        }
                    }
                );
            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnPlus: function(){
        var self = this;
        $('a.btn-add-cai').click(function() {
            var id          = $(this).attr('data-id');
            var zhuoHaoId   = $(this).attr('data-zhuohao-id');
            $('#add-cai-title').html($('#zhuo-hao-item-' + zhuoHaoId + " h3.title").text() + '客人加菜或点单');
            $('#add-cai-modal').modal('show');
            $('#cur-order-id').val(id);
            setTimeout(function() {
                $('#btn-cai-query').val('').focus();
            }, 1000);
        });
        $('a.btn-plus').click(function(){
            var that    = $(this);
            var id      = that.attr('data-id');
            var orderId = $('#cur-order-id').val();
            var caiNumber  = $(this).parent().siblings('.cai-number').children('.add-cai-number').val();
            try{
                HHJsLib.isEmpty(id, '编号');
                HHJsLib.isEmpty(orderId, '餐桌号');
                if(HJZCommon.isLoading == true) {
                    return;
                }
                HHJsLib.isEmpty(caiNumber, '数量');
                HJZCommon.isLoading = true;
                HHJsLib.info('正在操作加菜中，请稍等...');
                $.getJSON(
                    queryUrl + 'admin/diancan/aplus',
                    {id: id, order_id: orderId, number: caiNumber},
                    function(response){
                        HJZCommon.isLoading = false;
                        if(response.rs == false){
                            return HHJsLib.warn(response.message);
                        }
                        HHJsLib.succeed('加菜操作成功！');
                        var data    = response.data;
                        var tpl     = $('#plus-goods-item-tpl').html();
                        tpl         = tpl.replace(/{order_goods_id}/ig, data.goods_id)
                        .replace(/{id}/ig, orderId)
                        .replace(/{name}/ig, data.name)
                        .replace(/{price}/ig, data.price)
                        .replace(/{vip_price}/ig, data.vip_price)
                        .replace(/{src_price}/ig, data.src_price)
                        .replace(/{number}/ig, data.number)
                        .replace(/{order_id}/ig, orderId)
                        .replace(/{order_goods_id}/ig, data.id)
                        .replace(/{printer_id}/ig, data.printer_id)
                        .replace(/{number}/ig, data.number)
                        .replace(/{discount}/ig, data.discount)
                        .replace(/{total_price}/ig, data.total_price);
                        $('#data-grid-box-' + orderId).find('tbody').prepend(tpl);
                        $('#item-total-number-' + orderId).html(data.total_number);
                        $('#item-total-amount-' + orderId).html(data.amount);
                        $('strong.src-amount-' + orderId + " span.amount").html(data.src_amount);
                        $('#item-total-src-amount-' + orderId).html(data.src_amount);
                        $('#item-pay-money-' + orderId).html(data.pay_money);
                        if(parseFloat(data.youhui) > 0){
                            $('#use-youhui-' + orderId).html('优惠：' + response.data.youhui + ' 元 ').show();
                        }else{
                            $('#use-youhui-' + orderId).hide();
                        }
                        $('#plus-goods-item-' + id).addClass('hide');
                        self.bindResetPrint('#zd-od-item-' + data.goods_id + ' a.btn-reset-print');
                        self.bindBtnPrintCai('#zd-od-item-' + data.goods_id + ' a.btn-print-cai');
                        self.bindBtnTui();
                    }
                );

            }catch(e){
                return HHJsLib.warn(e);
            }
        });
    },
    bindBtnCaiQuery: function(){
        $('#btn-cai-query').keyup(function(event){
            var that        = $(this);
            var keyword     = that.val();
            var ids         = new Array();
            var words       = new Array();
            for(var index in goodsList){
                var item = goodsList[index];
                if((item.first_word.indexOf(keyword.toUpperCase()) >= 0) || item.name.indexOf(keyword) >= 0){
                    ids.push(item.id);
                    words.push(item.first_word);
                }
            }
            $('#add-cai-modal').find('ul.nav-tabs li').removeClass('active');
            $('#add-cai-modal').find('ul.nav-tabs li:first').addClass('active');
            $('#add-cai-modal').find('div.tab-pane').removeClass('active');
            $('#goods-cat-item-0').addClass('active');
            $('#goods-cat-item-0').find('tr.plus-goods-item')
            .addClass('hide').removeClass('search-done');
            for(var index in ids){
                var id = ids[index];
                $('#plus-goods-item-' + id).removeClass('hide').addClass('search-done');
            }
        }).bind('keydown', function(e) {
            if (e.keyCode != 13) {
                return;
            }
            $('#goods-cat-item-0 tr.search-done').first().find('a.btn-plus').click();
        });
    }
});
